//
//  BiaoQian.m
//  XRSquare
//
//  Created by 穆相臣 on 2018/8/31.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "BiaoQian.h"

@interface BiaoQian ()
{
    NSMutableArray * content;
    UIView * contentView;
    UIButton * addButton;
}
@end

@implementation BiaoQian

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        content = [NSMutableArray array];
        
        contentView = [[UIView alloc]initWithFrame:self.bounds];
        [self addSubview:contentView];
        
        addButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0,(ScreenWidth - 40)/5, 20)];
        addButton.layer.cornerRadius = 5;
        addButton.backgroundColor = [UIColor blackColor];
        addButton.titleLabel.font = [UIFont systemFontOfSize:10];
        [addButton setTitle:@"选择标签" forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:addButton];
    }
    return self;
}

-(void)addAction
{
    [self.delegate addBiaoQian];
}

-(void)insertCode:(NSDictionary *)code
{
    [content addObject:code];
    [self rearrange];
}

-(void)deleteAction:(UIButton *)delete
{
    [content removeObjectAtIndex:delete.tag];
    [self rearrange];
}

-(void)rearrange
{
    for (UIView * view in contentView.subviews)
    {
        [view removeFromSuperview];
    }
    for (int i = 0; i < [content count]; i ++)
    {
        UIButton * typeButton = [[UIButton alloc]initWithFrame:CGRectMake(((ScreenWidth - 40)/5 + 5) * i, 0, (ScreenWidth - 40)/5, 20)];
        typeButton.tag = i;
        typeButton.backgroundColor = [UIColor blackColor];
        [typeButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        typeButton.titleLabel.font = [UIFont systemFontOfSize:9];
        typeButton.layer.cornerRadius = 5;
        [typeButton setTitle:[[content objectAtIndex:i]objectForKey:@"Name"] forState:UIControlStateNormal];
        [contentView addSubview:typeButton];
        
        UIImageView * smallDelete = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 40)/5 - 10, -5, 15, 15)];
        smallDelete.image = [UIImage imageNamed:@"关闭2-fill"];
        [typeButton addSubview:smallDelete];
    }
    if ([content count] < 5)
    {
        addButton.hidden = NO;
        addButton.frame = CGRectMake(((ScreenWidth  - 40)/5 + 5) * [content count], 0, (ScreenWidth - 40)/5, 20);
    }
    else
    {
        addButton.hidden = YES;
    }
}

-(NSArray *)output
{
    return content;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
